package com.gy.yemall.yemallproduct.exception;

import com.gy.common.exception.CodeException;
import com.gy.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice
public class YemallControllerExceptionAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item) -> {
            String defaultMessage = item.getDefaultMessage();
            String field = item.getField();
            map.put(field, defaultMessage);
        });
        return R.error(CodeException.VAILD_EXCEPTION.getCode(), CodeException.VAILD_EXCEPTION.getMsg())
                .put("data", map);
    }

    @ExceptionHandler(value = Exception.class)
    public R handleOtherException(Exception e) {
        return R.error(CodeException.UNKNOW_EXCEPTION.getCode(), CodeException.UNKNOW_EXCEPTION.getMsg());
    }
}
